package com.sbl.bajw.common.web;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.httpclient.util.DateParseException;
import org.apache.commons.httpclient.util.DateUtil;

import com.sbl.bajw.common.Page;

public class RequestUnit {
	
	  static String pageSizeParmName = "grid_pageSize";
	  static String pageIndexParmName = "grid_pageIndex";
	  static String orderParmName = "grid_order";
	 
	 static  List<String> parsePatterns = Arrays.asList( 
			 "yyyy-MM-dd HH:mm:ss",  
			 "yyyy/MM/dd HH:mm:ss", 
			 "yyyy-MM-dd HH:mm",
			 "yyyy/MM/dd HH:mm",
	         "yyyy-MM-dd",	          
	         "yyyy/MM/dd"	         
	);
	 
	public static FileItem getFileItem(String name)
	{
		List<FileItem> items = WebContext.getFileItems();
		if(items == null)
		{
			return null;
		}
		for (FileItem fileItem : items) {
			boolean isForm = fileItem.isFormField();
			String fileName = fileItem.getFieldName();
			if(!isForm&&fileName.equals(name)&&fileItem.getSize()>0)
			{
				return fileItem;
			}
		}
		return null;
	}

	public static String getController()
	{
		if(UriInfos().length > 1)
		{
			return UriInfos()[1];
		}
		else
		{
			return null;
		}
	}
	
	public static String getAction()
	{
		if(UriInfos().length > 2)
		{
			return UriInfos()[2];
		}
		else
		{
			return null;
		}
	}
	
	public static String getView()
	{
		String[] infos = UriInfos();
		if(infos.length > 0)
		{
			return infos[infos.length-1];
		}
		else
		{
			return null;
		}
	}
	
	public static String getId()
	{
		if(UriInfos().length > 3)
		{
			return UriInfos()[3];
		}
		else
		{
			return null;
		}
	}
	
	public static Integer getPageSize()
	{
		Integer pageLength = getInt(pageSizeParmName); 
		if(pageLength == null)
		{
			return 30;
		}
		return pageLength;
	}
	
	public static Integer getPageIndex()
	{
		Integer PageIndex = getInt(pageIndexParmName); 
		if(PageIndex == null)
		{
			return 1;
		}
		return PageIndex;
	}
	
	public static String getOderString()
	{
		String orderString = getString(orderParmName); 
		return orderString;
	}
	
	public static Page getPage(){
		Page page = new Page();
		page.setPageIndex(getPageIndex());
		page.setPageSize(getPageSize());
		page.setOrderString(getOderString());
		return page;
	}
		
	public static String[] UriInfos()
	{
		String servletPath = WebContext.getRequest().getPathInfo();
		String[] infos = servletPath.split("/");
		return infos;
	}
	
	public static String getString(String paramName)
	{
		String value = getParameter(paramName);
		return value;
	}
	
	public static Integer getInt(String paramName)
	{
		try 
		{
			int value = Integer.parseInt(getParameter(paramName).trim());
			return value;
		} 
		catch (Exception e) 
		{
			return null;
		}		
	}
	
	public static BigDecimal getBigDecimal(String paramName)
	{
		try 
		{
			double dValue = getDouble(paramName);
			BigDecimal value = new BigDecimal(dValue);
			return value;
		} 
		catch (Exception e) 
		{
			return null;
		}		
	}
	
	public static Double getDouble(String paramName)
	{
		try 
		{
			double value = Double.parseDouble(getParameter(paramName));
			return value;
		} 
		catch (Exception e) 
		{
			return null;
		}		
	}
	
	public static Date getDate(String paramName)
	{
		try 
		{
			Date value = DateUtil.parseDate(getParameter(paramName),parsePatterns);
			return value;
		} 
		catch (Exception e) 
		{
			return null;
		}		
	}
	
	public static Timestamp getTimestamp(String paramName)
	{
		try 
		{
			String valueStr = getParameter(paramName);
			Timestamp value = parseDate(valueStr);
			return value;
		} 
		catch (Exception e) 
		{
			return null;
		}		
	}
	
	public static HashMap<String, Object> getHashMapParmO(){
		@SuppressWarnings("unchecked")
		Enumeration<String> names = WebContext.getRequest().getParameterNames();
		HashMap<String, Object> parm = new HashMap<String, Object>();
		while(names.hasMoreElements()){
			String name = names.nextElement();
			String value = getString(name);
			if(name.indexOf("@like") > 0){
				if(value != null && !value.equals("")){
					value = "%" + value + "%";
				}
				name = name.replaceAll("@like", "");
			}
			parm.put(name, value);
		}
		return parm;
	}
	
	public static HashMap<String, String> getHashMapParmS(){
		@SuppressWarnings("unchecked")
		Enumeration<String> names = WebContext.getRequest().getParameterNames();
		HashMap<String, String> parm = new HashMap<String, String>();
		while(names.hasMoreElements()){
			String name = names.nextElement();
			String value = getString(name);
			if(name.indexOf("@like") > 0){
				if(value != null && !value.equals("")){
					value = "%" + value + "%";
				}
				name = name.replaceAll("@like", "");
			}
			parm.put(name, value);
		}
		return parm;
	}
	
	public static HashMap<String, String> getHashMapParmSFileItem(){
		HashMap<String, String> parm = new HashMap<String, String>();

		List<FileItem> items =WebContext.getFileItems();
		if(items != null)
		{
			for (FileItem item : items) {
	            if (item.isFormField()) {
	                String fieldname = item.getFieldName();
                	String fieldvalue = null;
					try {
						fieldvalue = item.getString("UTF-8");
						parm.put(fieldname, fieldvalue);
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }
	        }
		}
		
		return parm;
	}
	
	public static <T> T getModel(Class<T> modelClass)
	{
		Field[] fields = modelClass.getDeclaredFields();
		try 
		{
			T model = modelClass.newInstance();
			for (Field field : fields) 
			{
				String methodName = "set" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
				Method[] methods = modelClass.getMethods();  
				Method method = null;
				
				for (Method m : methods) {
					if(m.getName().equals(methodName))
					{
						method = m;
						break;
					}
				}
				
				if(method == null){
					continue;
				}
				
				Class<?> fieldType = field.getType();
				if(fieldType.equals(String.class))
				{
					String value = getString(field.getName());
					method.invoke(model, value);
				}
				else if(fieldType.equals(Integer.class))
				{
					Integer value = getInt(field.getName());
					
					method.invoke(model, value);
				}
				else if(fieldType.equals(Date.class))
				{
					Date value = getDate(field.getName());
					method.invoke(model, value);
				}
				else if(fieldType.equals(Timestamp.class))
				{
					Timestamp value = getTimestamp(field.getName());
					method.invoke(model, value);
				}
				else if(fieldType.equals(Double.class))
				{
					Double value = getDouble(field.getName());
					method.invoke(model, value);
				}
				else if(fieldType.equals(BigDecimal.class))
				{
					BigDecimal value = getBigDecimal(field.getName());
					method.invoke(model, value);
				}
			}
			return model;
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			return null;
		} 
	}

	public static String getParameter(String paramName)
	{
		String result =  WebContext.getRequest().getParameter(paramName);
		if(result != null)
		{
			return result;
		}
		
		List<FileItem> items =WebContext.getFileItems();
		if(items != null)
		{
			for (FileItem item : items) {
	            if (item.isFormField()) {
	                String fieldname = item.getFieldName();
	                
	                if(fieldname.equals(paramName))
	                {
	                	String fieldvalue = null;
							try {
								fieldvalue = item.getString("UTF-8");
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
	                	return fieldvalue;
	                }
	            }
	        }
		}
		
		return result;		 
	}
	
	public static void setAttr(String key,Object value)
	{
		WebContext.getRequest().setAttribute(key, value);
	}
	
	public static Timestamp parseDate(String dateStr) throws DateParseException
	{		
		for (String formatStr : parsePatterns) {
			
			SimpleDateFormat df = new SimpleDateFormat(formatStr);
			try 
			{
				Date date = df.parse(dateStr);
				Timestamp value = new Timestamp(date.getTime());
				return value;
			}
			catch (Exception e) 
			{
			}
		}
		return null;
	}
}